<template>
	<base-layout simple>
		<article class="base-layout__inner column">
			<div class="disease-management">
				<div class="disease-management__title">疾病管理</div>

				<div class="disease-management__content">
					<!-- 查询条件 -->
					<tiny-form ref="tinyForm" :schema="formSchema" :model="queryParams" layout="inline"></tiny-form>

					<!-- 创建按钮 -->
					<div class="disease-management__actions">
						<t-button theme="primary" @click="handleCreate">
							<template #icon>
								<add-icon />
							</template>
							创建疾病分类
						</t-button>
					</div>

					<!-- 表格 -->
					<t-table
						row-key="id"
						:columns="tableSchema"
						:data="tableData"
						bordered
						size="small"
						:loading="loading"
					></t-table>
				</div>
			</div>
		</article>

		<!-- 编辑/创建弹框 -->
		<t-dialog
			:visible="editDialogVisible"
			:header="isCreateMode ? '创建疾病分类' : '编辑疾病分类'"
			width="500px"
			:confirm-btn="{ content: '保存', loading: editLoading }"
			@confirm="handleSaveEdit"
			@close="handleCloseEdit"
		>
			<t-form
				ref="editForm"
				:data="editFormData"
				:rules="editFormRules"
				label-align="left"
				label-width="80px"
			>
				<t-form-item label="分类名称" name="name">
					<t-input v-model="editFormData.name" placeholder="请输入分类名称" />
				</t-form-item>
				<t-form-item label="分类描述" name="description">
					<t-textarea
						v-model="editFormData.description"
						placeholder="请输入分类描述"
						:autosize="{ minRows: 3, maxRows: 6 }"
					/>
				</t-form-item>
				<t-form-item label="状态" name="isActive">
					<t-select v-model="editFormData.isActive" placeholder="请选择状态">
						<t-option :value="1" label="启用" />
						<t-option :value="0" label="禁用" />
					</t-select>
				</t-form-item>
			</t-form>
		</t-dialog>
	</base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import TinyForm from '@/components/tiny/TinyForm.vue';
import { Button as TButton, Tag as TTag, DialogPlugin as TDialog } from 'tdesign-vue';
import { getDiseaseList, deleteDisease, updateDisease, createDisease } from '@/api/disease';
import { Edit2Icon, DeleteIcon, AddIcon } from 'tdesign-icons-vue';

export default {
	name: 'OperationDisease',
	components: {
		BaseLayout,
		TinyForm,
		AddIcon
	},
	data() {
		return {
			loading: false,
			editLoading: false,
			editDialogVisible: false,
			isCreateMode: false, // 是否为创建模式
			currentEditId: null,
			// 编辑表单数据
			editFormData: {
				name: '',
				description: '',
				isActive: 1,
			},
			// 编辑表单验证规则
			editFormRules: {
				name: [
					{ required: true, message: '请输入分类名称', trigger: 'blur' },
					{ max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' },
				],
				description: [
					{ max: 200, message: '分类描述不能超过200个字符', trigger: 'blur' },
				],
				isActive: [
					{ required: true, message: '请选择状态', trigger: 'change' },
				],
			},
			// 查询表单配置
			formSchema: [
				{
					label: '分类名称',
					prop: 'name',
					component: 'Input',
					labelWidth: '80px',
					componentProps: {
						placeholder: '请输入分类名称',
					},
				},
				{
					label: '分类编码',
					prop: 'code',
					component: 'Input',
					labelWidth: '80px',
					componentProps: {
						placeholder: '请输入分类编码',
					},
				},
				{
					slots: (h) => {
						return h('span', {}, [
							h(
								TButton,
								{
									props: {
										theme: 'primary',
										variant: 'base',
									},
									on: {
										click: () => {
											this.handleSearch();
										},
									},
								},
								'查询'
							),
							h(
								TButton,
								{
									style: {
										marginLeft: '8px',
									},
									props: {
										theme: 'default',
										variant: 'base',
									},
									on: {
										click: () => {
											this.handleReset();
										},
									},
								},
								'重置'
							),
						]);
					},
				},
			],
			// 表格配置
			tableSchema: [
				{
					colKey: 'name',
					title: '分类名称',
					width: 150,
				},
				{
					colKey: 'code',
					title: '分类编码',
					width: 180,
					cell: (h, { row }) => {
						return row?.code
							? h(
									TTag,
									{
										props: {
											variant: 'light',
											theme: 'primary',
										},
									},
									row.code
								)
							: '-';
					},
				},
				{
					colKey: 'description',
					title: '分类描述',
					cell: (h, { row }) => {
						return row?.description || '-';
					},
				},
				{
					colKey: 'isActive',
					title: '状态',
					width: 80,
					cell: (h, { row }) => {
						return h(
							TTag,
							{
								props: {
									theme: row.isActive === 1 ? 'success' : 'danger',
									size: 'medium',
									variant: 'light',
								},
							},
							row.isActive === 1 ? '启用' : '禁用'
						);
					},
				},
				{
					title: '操作',
					width: 100,
					fixed: 'right',
					cell: (h, { row }) => {
						return h('span', {}, [
							h(
								TButton,
								{
									props: {
										variant: 'text',
										theme: 'primary',
										size: 'small',
									},
									on: {
										click: () => {
											this.handleEdit(row);
										},
									},
								},
								[h(Edit2Icon)]
							),
							h(
								TButton,
								{
									props: {
										variant: 'text',
										theme: 'danger',
										size: 'small',
									},
									on: {
										click: () => {
											this.handleDelete(row);
										},
									},
								},
								[h(DeleteIcon)]
							),
						]);
					},
				},
			],
			tableData: [],
			// 查询参数
			queryParams: {
				name: '',
				code: '',
				isActive: null,
			},
		};
	},
	mounted() {
		this.getList();
	},
	methods: {
		// 获取列表数据
		async getList() {
			this.loading = true;
			try {
				const res = await getDiseaseList(this.queryParams);
				console.log(res);
				this.tableData = res?.data?.data ?? [];
			} catch (error) {
				console.error('获取疾病分类列表失败:', error);
				this.tableData = [];
				this.$message.error('获取数据失败');
			} finally {
				this.loading = false;
			}
		},

		// 查询
		handleSearch() {
			this.getList();
		},

		// 重置
		handleReset() {
			this.queryParams = {
				name: '',
				code: '',
				isActive: null,
			};
			// 重置表单
			this.$refs.tinyForm?.reset();
			this.getList();
		},

		// 创建
		handleCreate() {
			this.isCreateMode = true;
			this.currentEditId = null;
			this.editFormData = {
				name: '',
				description: '',
				isActive: 1,
			};
			this.editDialogVisible = true;
		},

		// 编辑
		async handleEdit(row) {
			try {
				this.isCreateMode = false;
				this.currentEditId = row.id;

				this.editFormData = {
					name: row.name || '',
					description: row.description || '',
					isActive: row?.isActive ?? 0,
				};

				this.editDialogVisible = true;
			} catch (error) {
				console.error('获取分类详情失败:', error);
				this.$message.error('获取数据失败');
			}
		},

		// 保存编辑/创建
		async handleSaveEdit() {
			try {
				// 表单验证
				const valid = await this.$refs.editForm.validate();
				if (!valid) return;

				this.editLoading = true;

				const requestData = {
					name: this.editFormData.name,
					description: this.editFormData.description,
					isActive: this.editFormData.isActive,
				};

				let res;
				if (this.isCreateMode) {
					// 创建模式
					res = await createDisease(requestData);
				} else {
					// 编辑模式
					res = await updateDisease(this.currentEditId, requestData);
				}

				const { code, message } = res?.data ?? {};

				if (code === 200) {
					this.$message.success(this.isCreateMode ? '创建成功' : '更新成功');
					this.editDialogVisible = false;
					this.getList(); // 刷新列表
				} else {
					throw new Error(message ?? (this.isCreateMode ? '创建失败' : '更新失败'));
				}
			} catch (error) {
				console.error('保存失败:', error);
				this.$message.error(error.message || (this.isCreateMode ? '创建失败' : '更新失败'));
			} finally {
				this.editLoading = false;
			}
		},

		// 关闭编辑弹框
		handleCloseEdit() {
			this.editDialogVisible = false;
			this.isCreateMode = false;
			this.currentEditId = null;
			this.editFormData = {
				name: '',
				description: '',
				isActive: 1,
			};
			// 清除表单验证
			this.$nextTick(() => {
				this.$refs.editForm?.clearValidate();
			});
		},

		// 删除
		async handleDelete(row) {
			const confirmDialog = await new Promise((resolve) => {
				const instance = TDialog.confirm({
					header: '提示',
					body: `确定要删除分类"${row.name}"吗？`,
					confirmBtn: '确定',
					cancelBtn: '取消',
					onConfirm: () => {
						resolve(instance);
					},
				});
			});

			confirmDialog.hide();

			try {
				const res = await deleteDisease(row.id);
				const { code, message } = res?.data ?? {};

				if (code === 200) {
					this.$message.success('删除成功');
					this.getList();
				} else {
					throw new Error(message ?? '删除失败');
				}
			} catch (error) {
				console.error('删除失败:', error);
				this.$message.error('删除失败');
			}
		},
	},
};
</script>

<style lang="less" scoped>
.disease-management {
	&__title {
		color: #333;
		font-size: 18px;
		font-weight: 500;
		margin-bottom: 16px;
	}

	&__content {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	&__actions {
		display: flex;
		justify-content: flex-start;
	}
}
</style>